package com.moming.web.filter;

import javax.servlet.*;
import javax.servlet.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录验证的过滤器
 */
@WebFilter("/*")
public class LoginFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
        HttpServletRequest req = (HttpServletRequest) request;
        //判断访问的资源路径是否和登录注册相关,如果相关就放行
        String[] urls = {"/login.jsp","/loginServlet","register.jsp","/registerServlet","/css/","/imgs/","/checkCodeServlet"};
        //获取当前资源的访问路径
        String url = req.getRequestURL().toString();
        for (String u : urls) {
            //判断u是否包含url
            if(url.contains(u)){
            //放行
            chain.doFilter(request, response);
            //结束方法,后边的代码不用执行
            return;
            }
        }
        //判断session中是否有user对象
        HttpSession session = req.getSession();
        Object user = session.getAttribute("user");
        if(user!=null){
            //用户已登录
            //放行
            chain.doFilter(request, response);
        }else {
            //用户没有登录,或者session域已经销毁了
            req.setAttribute("msg", "您尚未登录!");
            //转发
            req.getRequestDispatcher("/login.jsp").forward(request,response);
        }

    }

    public void init(FilterConfig config) throws ServletException {
    }

    public void destroy() {
    }


}
